package com.express.gateway.spi.proxy.redirect;

import com.express.gateway.manage.entity.Api;
import com.express.gateway.manage.options.ServerEntranceRedirectOptions;
import com.express.gateway.spi.round.AfterHandler;

import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;

/**
 * VxApiRoute页面跳转处理器实现类
 *
 * @author flower
 */
public class RedirectProxyRouteHandlerImpl implements RedirectProxyRouteHandler {

    private boolean isNext;
    private ServerEntranceRedirectOptions redirectOptions;

    public RedirectProxyRouteHandlerImpl(boolean isNext, Api api) {
        super();
        this.isNext = isNext;
        JsonObject body = api.getServerEntrance().getBody();
        redirectOptions = ServerEntranceRedirectOptions.fromJson(body);
        if (redirectOptions == null) {
            throw new NullPointerException("页面跳转服务类型的配置文件无法装换为服务类");
        }
    }

    @Override
    public void handle(RoutingContext rct) {
        rct.response().putHeader("Location", redirectOptions.getUrl()).setStatusCode(302);
        if (isNext) {
            rct.put(AfterHandler.PREV_IS_SUCCESS_KEY, Future.<Boolean>succeededFuture(true));// 告诉后置处理器当前操作成功执行
            rct.next();
            return;
        }
        if (!rct.response().ended()) {
            rct.response().end();
        }
    }
}
